import Taro from '@tarojs/taro';
import {makeAutoObservable, runInAction} from 'mobx';
import {userType} from '@/types'
import http from '@/request'

const localData = Taro.getStorageSync('user-info') as userType | null

class Store {
  info: userType | null = localData?.id ? localData : {
    id: '',
    username: '',
    headImage: '',
    token: '',
    createTime: ''
  };
  updateInfo = (data?: userType) => {
    if (data) {
      return new Promise(resolve => {
        Taro.setStorageSync('user-info',data)
        this.info = data;
        resolve(true)
      })
    } else {
      return http.get('/disp/sys/user/getUserInfo').then(res => {
        const updateInfo = { ...(this.info || {}), ...(res.data || {}) }
        Taro.setStorageSync('user-info', updateInfo)
        runInAction(() => {
          this.info = updateInfo;
        })
      })
    }
  }
  constructor() {
    makeAutoObservable(this);
  }
}

export default new Store();
